package com.bric.sqlFile;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Queue;

import org.apache.log4j.Logger;

import com.bric.common.String_File;
import com.bric.util.JdbcFactory;
import com.bric.util.StaticStr;

public class ExcuteSql extends Thread{
	private static final Logger log=Logger.getLogger(ExcuteSql.class);
	Queue<File> Filequeue=SqlFile.Filequeue;
	@Override
	public void run() {
		while(Filequeue.size()>0){
			File f=Filequeue.poll();
			String sql=String_File.file2String(f);
			log.info("当前执行的sql是"+sql);
//			String_File.str2File(f.getName(), sql, "D:/data/temp1/");
			Connection conn=null;
			PreparedStatement ps=null;
			try {
				conn=JdbcFactory.getConnection();
				int index=f.getName().indexOf("_");
				log.info("找到的下标是"+index);
				if(index>0){
					log.info("执行带库名的语句...");
					if(!sql.endsWith(")")){
						log.info("非正常结尾的文件名是"+f.getName());
						int lastInd=sql.lastIndexOf(")");
						sql=sql.substring(0, lastInd);
					}
					String schema=f.getName().substring(0,index);
					String tableName=f.getName().substring(index+1);
					if(StaticStr.removeAllTable.contains(tableName.toLowerCase())){
						//需要先清空表
						String truncate=null;
						if(schema.startsWith("acc")){
							truncate="truncate table accfutures."+tableName;
						}
						if(schema.startsWith("Bric")){
							truncate="truncate table bricdata."+tableName;
						}
						log.info("执行清空表的语句"+truncate);
						conn.prepareStatement(truncate).execute();
					}
				}
				ps=conn.prepareStatement(sql);
				ps.executeUpdate();
			} catch (Exception e) {
				log.info("执行sql出现异常，文件是"+f.getName()+"异常信息是："+e.getMessage());
			}finally{
				JdbcFactory.close(conn, ps);
			}
		}
	}
}
